package com.pb.infra.oth.util;


import com.pb.infra.oth.entity.TreeVO;
import lombok.experimental.UtilityClass;

import java.util.ArrayList;
import java.util.List;

/**
 * 建树工具类
 *
 * @author 贾轶飞
 */
@UtilityClass
public class TreeUtil {

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeVO> List<T> buildByRecursive(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    public <T extends TreeVO> List<T> buildByRecursiveRootEmpty(List<T> treeNodes, Object root) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root==null&&(treeNode.getParentId()==null||treeNode.getParentId().toString().isEmpty())){
                treeNode.setParentId(null);
            }

            if (root==null&&treeNode.getParentId()==root){
                trees.add(findChildren(treeNode, treeNodes));
            }else
            if (!StringUtil.isEmpty(treeNode.getParentId()) && treeNode.getParentId().equals(root)) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeVO> T findChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public <T extends TreeVO> T findLevelChildren(T treeNode, List<T> treeNodes) {
        for (T it : treeNodes) {
            if (treeNode.getId().equals(it.getParentId())&&it.getLevel()!=null&& it.getLevel().equals(treeNode.getLevel()+1)) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<>());
                }
                treeNode.add(findLevelChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

    /**
     * 使用递归方法建树
     *泛型类中需要存在levelId
     * @param treeNodes
     * @return
     */
    public <T extends TreeVO> List<T> buildByRecursiveLevel(List<T> treeNodes, Object root, Integer level) {
        List<T> trees = new ArrayList<T>();
        for (T treeNode : treeNodes) {
            if (root.equals(treeNode.getParentId())&& treeNode.getLevel().equals(level)) {
                trees.add(findLevelChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }
}

